package cn.lr.basic.controller;

import cn.lr.basic.util.AjaxResult;
import cn.lr.basic.util.FastdfsUtil;
import jdk.nashorn.internal.ir.ReturnNode;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upLoad(@RequestPart(value = "file", required = true) MultipartFile file) {
        String filename = file.getOriginalFilename(); // 获取文件路径名称
        String sufName = filename.substring(filename.lastIndexOf(".") + 1); // 获取文件扩展名
        try {
            String relPath = FastdfsUtil.upload(file.getBytes(), sufName); // 获取上传路径
            return AjaxResult.me().setResultObj(relPath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，下次再来");
        }
    }

    /**
     * 文件删除
     * @param path
     * @return
     */
    @DeleteMapping // /group1/M00/03/57/rBE3kWJBshiAF5WOAAFSzi-eYSs656.jpg
    public AjaxResult delete(@RequestParam(value = "path",required = true) String path) {
        try {
            String pathTmp = path.substring(1); // group1/M00/03/57/rBE3kWJBshiAF5WOAAFSzi-eYSs656.jpg
            String groupName = pathTmp.substring(0,pathTmp.indexOf("/")); // group1
            String remName = pathTmp.substring(pathTmp.indexOf("/") + 1); // M00/03/57/rBE3kWJBshiAF5WOAAFSzi-eYSs656.jpg
            FastdfsUtil.delete(groupName,remName); // 传入参数，删除图片
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，下次再来");
        }
    }
}
